package org.jeecg.modules.zhouAdmin.admin.alipayrefund;

import com.alipay.api.AlipayApiException;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeRefundRequest;
import org.springframework.beans.factory.annotation.Autowired;

import java.math.BigDecimal;
import java.util.UUID;

public class RefundAlipay {

    @Autowired
    DefaultAlipayClient getDefaultAlipayClient;

    static DefaultAlipayClient client = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key
            , "json", "utf-8", AlipayConfig.alipay_public_key, "RSA2");

    /**
     * 订单退款（部分退款）
     *
     * @param sn     订单编号 必填
     * @param amount 团款金额 必填
     * @param reason 退款原因
     */
    public String refund(String sn, String amount, String reason) {
        String result = "";
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        request.setBizContent(AlipayUtil.getContentRefund(sn, new BigDecimal(amount), reason, UUID.randomUUID().toString()));
        try {
            result = client.execute(request).getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 全额退款
     * 全额退款的金额必须和支付金额一致，不用填写退款号
     *
     * @param sn     商户号(也就是订单编号)
     * @param amount 退款金额
     * @param reason 退款原因
     */
    public String refundAll(String sn, String amount, String reason) {
        String result = "";
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        request.setBizContent(AlipayUtil.getContentRefundAll(sn, new BigDecimal(amount), reason));
        try {
            result = client.execute(request).getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return result;
    }
}
